package com.yanx.system.web.command;

import com.yanx.common.command.Executor;
import com.yanx.common.core.command.VoidCommand;
import com.yanx.common.exception.BusinessException;
import com.yanx.common.utils.String_;
import com.yanx.system.base.command.SysDeptUpdateCmd;
import com.yanx.system.base.domain.entity.SysDept;
import com.yanx.system.base.domain.manager.SysDeptManager;
import com.yanx.system.base.model.dto.SysDeptDto;
import com.yanx.system.web.infra.constant.UserConstants;
import lombok.AllArgsConstructor;

/**
 * 部门 编辑命令
 *
 * @author: gotanks
 * @create: 2023-2-9
 */
@AllArgsConstructor
public class SystemDeptEditCmd extends VoidCommand {
    private SysDeptDto dept;

    @Override
    public void handler(Executor executor) {
        SysDeptManager sysDeptManager = executor.getReceiver(SysDeptManager.class);
        Long deptId = dept.getId();
//        deptService.checkDeptDataScope(deptId);
        if (sysDeptManager.checkDeptNameUnique(dept.getDeptName(), dept.getParentId(), dept.getId())) {
            throw new BusinessException("修改部门'{}'失败，部门名称已存在", dept.getDeptName());
        } else if (dept.getParentId().equals(deptId)) {
            throw new BusinessException("修改部门'{}'失败，上级部门不能是自己", dept.getDeptName());
        } else if (String_.equals(UserConstants.DEPT_DISABLE, dept.getStatus()) && sysDeptManager.hasNormalChildByDeptId(deptId)) {
            throw new BusinessException("该部门包含未停用的子部门！");
        }
//        dept.setUpdateBy(getUsername());

        SysDept newParentDept = sysDeptManager.getById(dept.getParentId());
        if (newParentDept != null) {
            String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getId();
            dept.setAncestors(newAncestors);
            sysDeptManager.updateChildrenAncestorsByDeptId(deptId, newAncestors);
        }

        executor.execute(new SysDeptUpdateCmd(dept.getId(), dept));

    }
}